package com.jiali.backend.Utils;


import cn.hutool.jwt.JWTUtil;
import com.jiali.backend.model.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.jiali.backend.constant.UserConstant.USER_LOGIN_STATE;

@Component
public class UserServiceUtils {

    String SALT = "JiaLi";//密码加密盐值
    String SECRET_KEY = "FancyLi";//token秘钥

    /**
     * 信息脱敏
     */
    public User safeUser(User user) {
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setUsername(user.getUsername());
        safeUser.setUserAccount(user.getUserAccount());
        safeUser.setAvatarUrl(user.getAvatarUrl());
        safeUser.setPhone(user.getPhone());
        safeUser.setUserRole(user.getUserRole());
        safeUser.setUpdateTime(user.getUpdateTime());
        return safeUser;
    }

    /**
     * 加密密码
     */
    public String encryptionPassword(String password) {
        return DigestUtils.md5DigestAsHex((SALT + password).getBytes());
    }

    public String generateToken(User user) {
        String secretKey = SECRET_KEY;
        Date expireDate = new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000);
        //载荷
        Map<String, Object> payLoad = new HashMap<>();
        payLoad.put("id", user.getId());
        payLoad.put("username", user.getUsername());
        payLoad.put("userAccount", user.getUserAccount());
        payLoad.put("userRole", user.getUserRole());
        //签发时间
        payLoad.put("iatDate", new Date(System.currentTimeMillis()).toString());
        payLoad.put("expireDate", expireDate.toString());
        return JWTUtil.createToken(payLoad, secretKey.getBytes());
    }

    public Map<String, Object> parseToken(String token) {
        if (validateToken(token)) {
            return JWTUtil.parseToken(token).getPayloads();
        }
        return new HashMap<>();
    }

    public boolean validateToken(String token) {
        String secretKey = SECRET_KEY;
        return JWTUtil.verify(token, secretKey.getBytes());
    }

    //判断是否为管理员
    public Boolean IsAdmin(HttpServletRequest httpRequest) {
        User currentUser = (User) httpRequest.getSession().getAttribute(USER_LOGIN_STATE);
        return currentUser.getUserRole() == 1;
    }

    //获取当前用户
    public User getCurrentUser(HttpServletRequest httpRequest) {
        return (User) httpRequest.getSession().getAttribute(USER_LOGIN_STATE);
    }
}
